/*
 * @[H]:  Copyright (c) 2021 Phytium Information Technology, Inc. 
 * 
 *  SPDX-License-Identifier: Apache-2.0. 
 * 
 * @Date: 2021-07-15 10:14:37
 * @LastEditTime: 2021-09-06 14:56:47
 * @Description:  Description of file
 * @Modify History: 
 * * * Ver   Who        Date         Changes
 * * ----- ------     --------    --------------------------------------
 */

#include "f_iomux.h"
#include "f_gpio.h"
#include "f_spi.h"
#include "parameters.h"
#include "ft_debug.h"
#include "interrupt.h"
// #include "gicv3.h"
#include "generic_timer.h"
#include "sdkconfig.h"

#define SPI_TEST_DEBUG_TAG "SPI_TEST"
#define SPI_TEST_ERROR(format, ...) FT_DEBUG_PRINT_E(SPI_TEST_DEBUG_TAG, format, ##__VA_ARGS__)
#define SPI_TEST_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(SPI_TEST_DEBUG_TAG, format, ##__VA_ARGS__)
#define SPI_TEST_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(SPI_TEST_DEBUG_TAG, format, ##__VA_ARGS__)

FSpi test_spi0;
FGpio gpio_port1;
u32 fin_flg;

static void FSpiTestFinCallback(void *args)
{
    *(u32 *)args = 1;
}

void IrqTestInit(void)
{
    /* interrupt init */
}

void FSpiTestInit(void)
{
    u32 pin_value = 0;
    u8 tx_cmd = 0x9f;
    u8 id_buf[3] = {0};
    FIomuxSetFun(FSPI0_IOMUX_CSN0_OFFSET, FUN1);
    FGpioCfgInitialize(&gpio_port1, FGpioLookupConfig(1));
    FGpioSetDirection(&gpio_port1, F_GPIO_A_PIN5, F_GPIO_DIRECTION_OUTPUT);
    FSpiCfgInitialize(&test_spi0, FspiLookupConfig(0));
    FSpiSetOptions(&test_spi0, FSPI_OPTION_SPEED, 4000000);

#ifdef CONFIG_SPI_DEMO_IRQ
    FSpiIrqCallbackRegister(&test_spi0, FSPI_IRQ_FIN_CALLBACK_REGISTER, FSpiTestFinCallback, &fin_flg);
    FSpiSetOptions(&test_spi0, FSPI_OPTION_WORK_MODE, FSPI_INTR_TRANSACTION);
    IrqTestInit();
    InterruptSetPriority(test_spi0.config.irq_num, 0);
    InterruptInstall(test_spi0.config.irq_num, (IrqHandler)FSpiInterruptHandler, &test_spi0, "spi0");
    InterruptUmask(test_spi0.config.irq_num);
#endif

#ifdef CONFIG_SPI_DEMO_POLL
    FGpioSetValue(&gpio_port1, F_GPIO_A_PIN5, 0);
    FSpiTransfer(&test_spi0, &tx_cmd, NULL, 1);
    FSpiTransfer(&test_spi0, NULL, id_buf, sizeof(id_buf));
    FGpioSetValue(&gpio_port1, F_GPIO_A_PIN5, 1);
#else
    FGpioSetValue(&gpio_port1, F_GPIO_A_PIN5, 0);
    FSpiTransfer(&test_spi0, &tx_cmd, NULL, 1);
    while (fin_flg == 0)
    {
    }
    fin_flg = 0;
    FSpiTransfer(&test_spi0, NULL, id_buf, sizeof(id_buf));
    while (fin_flg == 0)
    {
    }

    FGpioSetValue(&gpio_port1, F_GPIO_A_PIN5, 1);
#endif
    SPI_TEST_DEBUG_I("Get id: %x %x %x ", id_buf[0], id_buf[1], id_buf[2]);
}
